<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('checkLogin')) {
	function checkLogin() {
        $CI =& get_instance();
		if($CI->session->userdata('logged') != 1) {
			header('Location: /Login');
		}
	}
}	

	/**
	 * Get validation messages in different 
	 * languages and push them client-side
	 * for the jQuery validation.
	 *
	 * @access	public
	 * @param	string $message Help message lang id (found in CI language files)
	 * @param   int $id Desired id extension for the a and div 
	 * @param   string $extraClass allows adding another class to the icon href
	 * @return	string (HTML code)
	 */	
if ( ! function_exists('help')) {
	function help($message=NULL,$id=NULL,$extraClass=NULL) {
		$returnString  = '<a href="#" class="iconHelp help '.$extraClass.'" id="trigger_'.$id.'"></a>';
		$returnString .= '<div class="tooltip helpTip" style="width: 200px;" id="help_'.$id.'">';
		$returnString .= lang($message);
		$returnString .= '</div>';
		
		return $returnString;
	}
}	

/**
	 * makeTagJSON creates a simple JSON string for 
	 * our tag autocompleter 
	 *
	 * @access	public
	 * @param	array $array array of tags from database query 
	 * @return	string (JSON)
	 */	
if ( ! function_exists('makeTagJSON')) {
	function makeTagJSON($array) {
		if (empty($array)) {
			$jsonString = '[{}]';
		} else {
			$jsonString = '[';
			foreach($array as $item) {
                $tag = cleanStringTag($item['Tag']);
				$jsonString .= '{"ItemID":"'.$item['TID'].'","ItemName":"'.$tag.'"},';
			}
			$jsonString = substr($jsonString,0,-1);
			$jsonString .= ']';
		}
		
		return $jsonString;
	}
}

/**
	 * makeCategoryJSON creates a simple JSON string for
	 * our categories
	 *
	 * @access	public
	 * @param	array $array array of categories from database query
	 * @return	string (JSON)
	 */
if ( ! function_exists('makeCategoryJSON')) {
	function makeCategoryJSON($array) {
		if (empty($array)) {
			$jsonString = '[{}]';
		} else {
			$jsonString = '[';
			foreach($array as $item) {
				$jsonString .= '{"ItemID":"'.$item['CatID'].'","ItemName":"'.$item['MainCat'].'"},';
			}
			$jsonString = substr($jsonString,0,-1);
			$jsonString .= ']';
		}

		return $jsonString;
	}
}

/**
 * Industry Menu
 *
 * Generates a drop-down menu of industries.
 *
 * @access	public
 * @param	string	default industry
 * @param	string	classname
 * @param	string	menu name
 * @return	string
 */	
if ( ! function_exists('industry_menu'))
{
	function industry_menu($default = "", $class = "", $name = 'industries', $width="", $tabindex=NULL)
	{
		$menu = '<select name="'.$name.'" id="'.$name.'" tabindex="'.$tabindex.'" style="width: '.$width.'px;" ';
	
		if ($class != '')
		{
			$menu .= ' class="'.$class.'"';
		}
	
		$menu .= ">\n";
        $menu .= "<option></option>";
	
		foreach (industries() as $key => $val)
		{
			$selected = ($default == $key) ? " selected='selected'" : '';
			$menu .= "<option value='{$key}'{$selected}>".lang($key)."</option>\n";
		}

		$menu .= "</select>";

		return $menu;
	}
}

function industries() {
	$industry['Accounting']                    = "Accounting";
	$industry['Advertising']                   = "Advertising";
	$industry['Aerospace']                     = "Aerospace";
	$industry['Airline']                       = "Airline";
	$industry['Automotive']                    = "Automotive";
	$industry['Banking']                       = "Banking";
	$industry['BioTech']                       = "BioTech";
	$industry['Broadcasting']                  = "Broadcasting";
	$industry['Chemical']                      = "Chemical";
	$industry['Computer Hardware/Supplies']    = "Computer Hardware/Supplies";
	$industry['Computer Software']             = "Computer Software";
	$industry['Construction']                  = "Construction";
	$industry['Consumer Products']             = "Consumer Products";
	$industry['Distribution']                  = "Distribution";
	$industry['Education']                     = "Education";
	$industry['Engineering']                   = "Engineering";
	$industry['Entertainment']                 = "Entertainment";
	$industry['Environmental']                 = "Environmental";
	$industry['Fashion']                       = "Fashion";
	$industry['Financial Planning/Services']   = "Financial Planning/Services";
	$industry['Food & Beverage']               = "Food & Beverage";
	$industry['Forestry']                      = "Forestry";
	$industry['Freight/Shipping']              = "Freight/Shipping";
	$industry['Fund Raising']                  = "Fund Raising";
	$industry['Government']                    = "Government";
	$industry['Graphic Design']                = "Graphic Design";
	$industry['Health and Fitness']            = "Health and Fitness";
	$industry['Healthcare']                    = "Healthcare";
	$industry['Import/Export Trade']           = "Import/Export Trade";
	$industry['Industrial Supplies/Equipment'] = "Industrial Supplies/Equipment";
	$industry['Insurance']                     = "Insurance";
	$industry['Interior Design']               = "Interior Design";
	$industry['Internet']                      = "Internet";
	$industry['Legal']                         = "Legal";
	$industry['Manufacturing']                 = "Manufacturing";
	$industry['Marketing']                     = "Marketing";
	$industry['Medical Supplies/Services']     = "Medical Supplies/Services";
	$industry['Mortgage Lending']              = "Mortgage Lending";
	$industry['Non-Profit']                    = "Non-Profit";
	$industry['Office Products']               = "Office Products";
	$industry['Oil and Gas']                   = "Oil and Gas";
	$industry['Other']                         = "Other";
	$industry['Packaging']                     = "Packaging";
	$industry['Paper']                         = "Paper";
	$industry['Payroll Services']              = "Payroll Services";
	$industry['Personnel/Employment']          = "Personnel/Employment";
	$industry['Pest Control']                  = "Pest Control";
	$industry['Pharmaceutical']                = "Pharmaceutical";
	$industry['Photography']                   = "Photography";
	$industry['Printing']                      = "Printing";
	$industry['Public Relations']              = "Public Relations";
	$industry['Publishing']                    = "Publishing";
	$industry['Real Estate']                   = "Real Estate";
	$industry['Restaurant']                    = "Restaurant";
	$industry['Retail']                        = "Retail";
	$industry['Securities/Commodities']        = "Securities/Commodities";
	$industry['Security']                      = "Security";
	$industry['Telecom']                       = "Telecom";
	$industry['Training']                      = "Training";
	$industry['Transportation']                = "Transportation";
	$industry['Travel']                        = "Travel";
	
	return $industry;
}

function renderHeaderButtons($buttonArray) {
    $buttonString = '';
    $style = '';
    if (isset($buttonArray)) {
        foreach($buttonArray as $key => $pageButton) {
            if (isset($pageButton[5])) {
                $buttonID = 'button'.$pageButton[5];
            } else {
                $buttonID = 'button'.$key;
            }
            if (isset($pageButton[6])) {
                if ($pageButton[6] == 'off') {
                    $style = 'style="display: none;"';
                }
            }
            $otherStuff = '';
            if (isset($pageButton[7])) {
                $otherStuff = $pageButton[7];
            }
            $buttonString .= '<button '.$style.' class="buttonExpand '.$pageButton[2].' '.$pageButton[3].'" itemID="'.$pageButton[4].'" id="'.$buttonID.'" title="'.$pageButton[1].'" '.$otherStuff.'><span class="buttonOuterSpan '.$pageButton[2].'"><span class="buttonDecorator '.$key.'">'.$pageButton[0].'</span></span></button>';
        }
    } else {
        $buttonString = '&nbsp;';
    }

    return $buttonString;
}

/**
 * makeUserArrayFromString: Convert a user string from a form submission in
 *                          the form of PID,Language|PID,Language|PID,Language...
 *                          into a PHP array
 *
 * @access	public
 * @param	string	userString
 * @return	array
 */
function makeUserArrayFromString($userString) {
    if (!empty($userString)) {
        $userArray = array();
        $array1 = explode('|',$userString);
        $a=0;
        foreach($array1 as $user) {
            if (!empty($user)) {
                $array2 = explode(',',$user);
                $userArray[$a] = array('PID' => $array2[0],'Language' => $array2[1]);
                $a++;
            }
        }
        return $userArray;
    } else {
        return false;
    }
}

if (!function_exists('imageResize')) {
    function imageResize($imageFilename,$maxW=NULL,$maxH=NULL,$expand=FALSE) {
        $imageSize = getimagesize($imageFilename);

        $imgW = $imageSize[0];
        $imgH = $imageSize[1];

        if ($maxW>0 && $maxH>0) {
            /*
             * Determine image orientation
             */
            if ($imgW>$imgH) {
                /*
                 * Horizontal
                 */
                $resizeRatio = abs($maxW/$imgW);
                $newW = ceil($imgW*$resizeRatio);
                $newH = ceil($imgH*$resizeRatio);
            } elseif ($imgH>$imgW) {
                /*
                 * Vertical
                 */
                $resizeRatio = abs($maxH/$imgH);
                $newW = ceil($imgW*$resizeRatio);
                $newH = ceil($imgH*$resizeRatio);
            } else {
                /*
                 * Square
                 */
                $resizeRatio = abs($maxH/$imgH);
                $newW = ceil($imgW*$resizeRatio);
                $newH = ceil($imgH*$resizeRatio);
            }
        } elseif ($maxW>0) {
            $resizeRatio = abs($maxW/$imgW);
            $newW = ceil($imgW*$resizeRatio);
            $newH = ceil($imgH*$resizeRatio);
        } elseif ($maxH>0) {
            $resizeRatio = abs($maxH/$imgH);
            $newW = ceil($imgW*$resizeRatio);
            $newH = ceil($imgH*$resizeRatio);
        }

        if ($expand == FALSE && ($maxW>$imgW || $maxH>$imgH)) {
            /*
             * Return the original image size
             */
            $newW = $imgW;
            $newH = $imgH;
        }

        return array($newW,$newH);
    }
}

if (!function_exists('getGravatar')) {
    /**
     * Get either a Gravatar URL or complete image tag for a specified email address.
     *
     * @param string $email The email address
     * @param string $s Size in pixels, defaults to 80px [ 1 - 512 ]
     * @param string $d Default imageset to use [ 404 | mm | identicon | monsterid | wavatar ]
     * @param string $r Maximum rating (inclusive) [ g | pg | r | x ]
     * @param boole $img True to return a complete IMG tag False for just the URL
     * @param array $atts Optional, additional key/value attributes to include in the IMG tag
     * @return String containing either just a URL or a complete image tag
     * @source http://gravatar.com/site/implement/images/php/
     */
    function getGravatar( $email, $s = 80, $d = 'mm', $r = 'g', $img = false, $atts = array() ) {
        $url = 'http://www.gravatar.com/avatar/';
        $url .= md5( strtolower( trim( $email ) ) );
        $url .= "?s=$s&d=$d&r=$r";
        if ( $img ) {
            $url = '<img src="' . $url . '"';
            foreach ( $atts as $key => $val )
                $url .= ' ' . $key . '="' . $val . '"';
            $url .= ' />';
        }
        return $url;
    }
}

/*
 * Take a tag string in the form of tag, tag, tag, tag,
 * and make each tag a link
 */
if (!function_exists('prepTagString')) {
    function prepTagString($tagString,$linkPrefix) {
        $tagArray = explode(',',$tagString);

        $tagLinkString = '';
        foreach($tagArray as $tag) {
            $tag = trim($tag);
            if (!empty($tag)) {
                $tagLinkString .= '<a href="'.$linkPrefix.'/'.$tag.'">'.$tag.'</a>, ';
            }
        }

        /*
         * Remove trailing comma
         */
        $tagLinkString = substr($tagLinkString,0,-2);
        return $tagLinkString;
    }
}

if (!function_exists('noCache')) {
    function noCache() {
        $CI =& get_instance();
        $CI->output->set_header("Pragma: no-cache");
        $CI->output->set_header("Cache-Control: no-store, no-cache, must-revalidate");
        $CI->output->set_header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    }
}

function createPlanData($plan=NULL) {
    global $accountLevelArray;
    $CI =& get_instance();

    $accountDesc = array();
    $accountVariableArray = array();
    $accountVars = array();
    foreach ($accountLevelArray as $account) {
        if ($account['fileSpace'] == 0) {
            $storageSpace = 'None';
        } else {
            $storageSpace = byte_format($account['fileSpace']);
        }

        if ($account['cost'] == 0) {
            $costPerMonth = 'Free!';
        } else {
            $costPerMonth = '$'.$account['cost'].'.00';
        }

        if ($account['projects'] == 100000) {
            $account['projects'] = 'Unlimited';
        }
        if ($account['teamMembers'] == 100000) {
            $account['teamMembers'] = 'Unlimited';
        }

        $accountDescTxt  = '<ul class="check">';
        $accountDescTxt .= '<li class="bigText">Cost per month: '.$costPerMonth.'</li>';
        $accountDescTxt .= '<li class="bigText">Active projects: '.$account['projects'].'</li>';
        $accountDescTxt .= '<li class="bigText">Team members: '.$account['teamMembers'].'</li>';
        $accountDescTxt .= '<li class="bigText">Storage space: '.$storageSpace.'</li>';
        $accountDescTxt .= '</ul>';
        $accountDesc[$account['name']] = $accountDescTxt;

        $accountVariableArray['cost']        = $costPerMonth;
        $accountVariableArray['projects']    = $account['projects'];
        $accountVariableArray['teamMembers'] = $account['teamMembers'];
        $accountVariableArray['storage']     = $storageSpace;
        $accountVars[$account['name']] = $accountVariableArray;
    }

    $data['accountDescriptions'] = $accountDesc;
    $data['selectedPlan'] = '';
    switch ($plan) {
        case 'free':
            $data['classFree'] = 'iconCheckOrange selected';
            $data['classSolo'] = 'iconCheckGray';
            $data['classShop'] = 'iconCheckGray';
            $data['classTeam'] = 'iconCheckGray';
            $data['acctDesc']  = $accountDesc['free'];
            $data['acctVars']  = $accountVars['free'];
            $data['billingTxtFreeDisplay'] = '';
            $data['billingTxtPaidDisplay'] = 'none';
            $data['selectedPlan'] = 'free_0';
            break;
        case 'solo':
            $data['classFree'] = 'iconCheckGray';
            $data['classSolo'] = 'iconCheckOrange selected';
            $data['classShop'] = 'iconCheckGray';
            $data['classTeam'] = 'iconCheckGray';
            $data['acctDesc']  = $accountDesc['solo'];
            $data['acctVars']  = $accountVars['solo'];
            $data['billingTxtFreeDisplay'] = 'none';
            $data['billingTxtPaidDisplay'] = '';
            $data['selectedPlan'] = 'solo_1';
            break;
        case 'shop':
            $data['classFree'] = 'iconCheckGray';
            $data['classSolo'] = 'iconCheckGray';
            $data['classShop'] = 'iconCheckOrange selected';
            $data['classTeam'] = 'iconCheckGray';
            $data['acctDesc']  = $accountDesc['shop'];
            $data['acctVars']  = $accountVars['shop'];
            $data['billingTxtFreeDisplay'] = 'none';
            $data['billingTxtPaidDisplay'] = '';
            $data['selectedPlan'] = 'shop_2';
            break;
        case 'team':
            $data['classFree'] = 'iconCheckGray';
            $data['classSolo'] = 'iconCheckGray';
            $data['classShop'] = 'iconCheckGray';
            $data['classTeam'] = 'iconCheckOrange selected';
            $data['acctDesc']  = $accountDesc['team'];
            $data['acctVars']  = $accountVars['team'];
            $data['billingTxtFreeDisplay'] = 'none';
            $data['billingTxtPaidDisplay'] = '';
            $data['selectedPlan'] = 'team_3';
            break;
        default:
            $data['classFree'] = 'iconCheckGray';
            $data['classSolo'] = 'iconCheckGray';
            $data['classShop'] = 'iconCheckGray';
            $data['classTeam'] = 'iconCheckGray';
            $data['acctDesc']  = '<span class="bigText">Please select a plan.</span>';
            $data['billingTxtFreeDisplay'] = 'none';
            $data['billingTxtPaidDisplay'] = 'none';
            break;
    }

    return $data;
}

function cachedFile($name, $attr=NULL) {
    $filetype = substr($name,strripos($name,'.')+1);

    /* Configuration options */
    $imgpath = 'images/';
    $csspath = 'css/';
    $jspath  = 'js/';

    switch ($filetype){
        case 'css':
            $output = '<link rel="stylesheet" type="text/css" href="'.BASE_URL.$csspath.$name;
            $output .= '?' . filemtime(ROOT_DIR . '/' . $csspath . $name) . '" ';
            if($attr){
             $output .= $attr . ' ';
            }
            $output .= '/>' . "\n";
            break;
        case 'js':
            $output = '<script type="text/javascript" src="'.BASE_URL.$jspath.$name;
            $output .= '?' . filemtime(ROOT_DIR . '/' . $jspath . $name) . '"';
            $output .= '></script>' . "\n";
            break;
        case 'jpg':
        case 'gif':
        case 'png':
            //This code will get run in any of the three cases above
            $output = '<img src="' . BASE_URL . $imgpath . $name;
            $output .= '?' . filemtime(ROOT_DIR . '/' . $imgpath . $name) . '"';
            $imgsize = getimagesize(ROOT_DIR . '/' . $imgpath . $name);
            $output .= ' ' . $imgsize[3];
            if($attr){
                $output .= ' ' . $attr;
            }
            $output .= ' />';
            break;
    }
    return $output;
}

/**
 * linkFile: appends the last modified date to a file as a cache busting
 * technique.
 *
 * @param string $path The file path
 * @param boolean $returnFullPath Return the full file path with timestamp or
 *                                just the timestamp
 * @return string The file path with the timespamp appended
 */
function linkFile($path,$returnFullPath=TRUE) {
    if (file_exists($path))
    {
        // get the file's timestamp
        $time = filemtime($path);

        // return a 'cache-busting' URL or just the timestamp
        if ($returnFullPath) {
            return $path . '?v=' . $time;
        } else {
            return $time;
        }
    }
}
?>